<template>
  <el-select
    v-model="selectedValues"
    filterable
    remote
    multiple
    :remote-method="remoteSearch"
    :loading="loading"
    placeholder="请选择人员"
    style="width: 100%"
    clearable
  >
    <el-option
      v-for="item in options"
      :key="item.personnelId"
      :label="`${item.personnelCode} - ${item.personnelName}`"
      :value="item.personnelId"
    >
      <div class="personnel-option">
        <div>{{ item.personnelCode }} - {{ item.personnelName }}</div>
        <div class="personnel-option-info">
          {{ item.supplierName }} | {{ item.levelName || getLevelName(item.level) }} |
          {{ item.monthlyRate }}元/月
        </div>
      </div>
    </el-option>
  </el-select>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch } from "vue";
import { getAvailablePersonnelList } from "@/api/attendance/orderPersonnel";
import { OrderPersonnelQuery } from "@/types/attendance/order/personnelRelation";

interface Personnel {
  personnelId: number;
  personnelCode: string;
  personnelName: string;
  supplierId: number;
  supplierName: string;
  level: string;
  levelName?: string;
  monthlyRate: number;
}

interface Props {
  modelValue: number[];
  orderId?: number;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => []
});

const emit = defineEmits(["update:modelValue"]);

const loading = ref(false);
const options = ref<Personnel[]>([]);
const selectedValues = ref<number[]>(props.modelValue || []);

// 远程搜索
async function remoteSearch(query: string) {
  if (query) {
    loading.value = true;
    try {
      const params: OrderPersonnelQuery = {
        pageNum: 1,
        pageSize: 50,
        personnelName: query
      };
      const { data } = await getAvailablePersonnelList(params);
      options.value = data.rows;
    } catch (error) {
      console.error("搜索人员失败:", error);
    } finally {
      loading.value = false;
    }
  } else {
    options.value = [];
  }
}

// 获取级别名称
function getLevelName(level?: string): string {
  if (!level) return "";

  const levelMap: Record<string, string> = {
    "01": "初级",
    "02": "中级",
    "03": "高级",
    "04": "专家"
  };

  return levelMap[level] || "";
}

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  val => {
    selectedValues.value = val;
  }
);

// 监听内部 selectedValues 变化
watch(selectedValues, val => {
  emit("update:modelValue", val);
});
</script>

<style scoped>
.personnel-option {
  display: flex;
  flex-direction: column;
}

.personnel-option-info {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>
